﻿using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Common;
using System.Collections.Generic;
using Xhelper.ApiGate;
using Models;
using System.Security.Claims;
using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using System;

namespace Web.Controllers
{

  /// <summary>
  /// APP 用户权鉴相关
  /// </summary>
  [Route("api/[controller]")]
  public class AuthController : BaseController
  {
    /// <summary>
    /// 获取检测单位列表
    /// </summary>
    /// <returns></returns>
    [HttpGet("[action]")]
    public async Task<IActionResult> getTestUnitList()
    {
      List<ApiHost> lis = new List<ApiHost>();
      foreach (var item in SiteConfig.Current.ApiHostList)
      {
        lis.Add(item.Value);
      }
      return await PublicTool.ReturnSuccess(lis);
    }

    /// <summary>
    /// 获取 token
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [HttpPost("[action]")]
    public async Task<IActionResult> GetToken([FromBody] ParmGenToken model)
    {
      var result = UserApi.CheckLogin(testUnitId, model);
      if (result["code"].ToString() != "0")
      {
        return await PublicTool.ReturnError(result["msg"]);
      }

      var _return = new Dictionary<string, string>();
      Dictionary<string, object> _data = (Dictionary<string, object>)result["data"];
      _return["uname"] = _data["username"].ToString();
      _return["uid"] = _data["id"].ToString();
      _return["regCode"] = _data["regCode"].ToString();
      _return["testUnitId"] = testUnitId;
      _return["testUnit"] = model.testUnit;

      var Claims = new ClaimsIdentity();
      Claims.AddClaim(new Claim(ClaimTypes.Name, _return["uname"]));
      Claims.AddClaim(new Claim(ClaimTypes.Role, "user"));
      Claims.AddClaim(new Claim("regCode", _return["regCode"]));
      Claims.AddClaim(new Claim("uid", _return["uid"]));

      var tokenHandler = new JwtSecurityTokenHandler();
      var key = Encoding.ASCII.GetBytes("Security:Tokens:Key");
      var tokenDescriptor = new SecurityTokenDescriptor
      {
        Issuer = "Security:Tokens:Issuer",
        Audience = "Security:Tokens:Audience",
        Subject = Claims,
        Expires = DateTime.UtcNow.AddDays(30),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
      };

      var _securityToken = tokenHandler.CreateToken(tokenDescriptor);
      var token = tokenHandler.WriteToken(_securityToken);

      _return["token"] = token;

      return await PublicTool.ReturnSuccess(_return);
    }

  }
}
